<template>
  <div class="chart">
    <div v-if="loading" class="loading">加载中...</div>
    <div ref="chartRef" class="monitorContainer" v-else />
  </div>
</template>

<script setup>
import * as echarts from 'echarts';
import { onMounted, onUnmounted, watch, ref, nextTick } from 'vue';

const props = defineProps({
  chartOption: {
    type: Object,
    default: () => ({
      xAxisData: [],
      yAxisName: '单位：元',
      seriesData: [],
      legendData: []
    })
  },
  loading: {
    type: Boolean,
    default: false
  }
});

// DOM 引用
const chartRef = ref(null);
let myChart = null;

// 颜色配置
const axisColor = ref('#D9D9D9');
const axisColor2 = ref('#999999');
const itemStyleColor = ref('#91B0FF');

// 构建 series
const getSeriesOption = () => {
  const data = props.chartOption.seriesData || [];
  if (!Array.isArray(data)) {
    console.warn('seriesData should be an array', data);
    return [];
  }

  return [
    {
      name: '销售额', // ✅ 为系列命名，与图例匹配
      type: 'bar',
      data: data,
      itemStyle: {
        color: itemStyleColor.value,
        // ✅ 使用 borderRadius 替代 barBorderRadius
        borderRadius: [4, 4, 0, 0]
      },
      barWidth: 14,
      barGap: '100%'
    }
  ];
};

// 初始化并设置图表
const setOption = () => {
  nextTick(() => {
    if (!chartRef.value) return;

    // 如果已有实例，先销毁
    if (myChart) {
      myChart.dispose();
    }

    myChart = echarts.init(chartRef.value);

    const option = {
      title: {
        text: '销售额分布',
        left: 'center',
        top: '10',
        textStyle: {
          color: '#333333',
          fontWeight: 'bolder',
          fontSize: 14
        }
      },
      grid: {
        left: 33,
        right: 30,
        top: 60,
        bottom: 5,
        containLabel: true
      },
      // ✅ 确保图例数据与系列数据匹配
      legend: {
        bottom: 0,
        data: props.chartOption.legendData && props.chartOption.legendData.length > 0 
              ? props.chartOption.legendData 
              : ['销售额'] // 默认显示销售额图例
      },
      xAxis: {
        type: 'category',
        data: props.chartOption.xAxisData || [],
        axisLine: { lineStyle: { color: axisColor.value } },
        axisTick: { show: true, lineStyle: { color: axisColor.value } },
        axisLabel: {
          interval: 0,
          align: 'center',
          color: axisColor2.value,
          formatter: function (value) {
            return value.length > 3 ? value.substring(0, 3) + '\n...' : value;
          }
        }
      },
      yAxis: {
        type: 'value',
        name: props.chartOption.yAxisName || '单位：元',
        nameTextStyle: { color: axisColor2.value },
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { color: axisColor2.value },
        splitLine: { lineStyle: { color: axisColor.value } }
      },
      series: getSeriesOption(),
      tooltip: {
        trigger: 'axis',
        formatter: '销售额：{c}<br />{b}',
        backgroundColor: '#FFFFFF',
        borderColor: '#eef3f8',
        borderWidth: 1,
        textStyle: { color: '#8C8C8C' },
        padding: 12
      }
    };

    myChart.setOption(option);

    // 监听窗口 resize
    window.addEventListener('resize', handleResize);
  });
};

// 处理窗口大小变化
const handleResize = () => {
  myChart?.resize();
};

// 组件挂载后初始化
onMounted(() => {
  setOption();
});

// 监听 chartOption 变化，自动更新图表
watch(
  () => props.chartOption,
  () => {
    if (myChart) {
      setOption();
    }
  },
  { deep: true }
);

// 组件卸载前销毁实例
onUnmounted(() => {
  if (myChart) {
    window.removeEventListener('resize', handleResize);
    myChart.dispose();
    myChart = null;
  }
});
</script>

<style lang="scss" scoped>
.chart {
  position: relative;
  display: inline-block;
  width: 50%;
  height: 100%;
}

.monitorContainer {
  width: 100%;
  height: 300px;

  & > div,
  & > canvas {
    width: 100% !important;
    height: 100% !important;
  }
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 300px;
  font-size: 14px;
  color: #999;
}
</style>